package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.DianZanReasonAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.LabelObject;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.widget.SearchBarView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/10/30.
 * 为什么赞Ta
 */

public class DianZanReasonActivity extends BaseActivity implements View.OnClickListener {

    private TextView title;
    private TextView tip;//提示语
    private RelativeLayout tipLayout;//空白页
    private RelativeLayout emptyLayout2;//空白页
    private TextView tipText;
    private Button callBack;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private DianZanReasonAdapter adapter;
    private DianZanReasonAdapter sadapter;
    private List<LabelObject> labels = new ArrayList<>();
    private List<LabelObject> slabels = new ArrayList<>();
    private SearchBarView searchBarView;
    private int page = 1;
    private int totalpage = 0;
    private int pageSize = 10;
    private int spage = 1;
    private int stotalpage = 0;
    private String keyWord = "";

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, DianZanReasonActivity.class);
        activity.startActivity(intent);
    }

    public static void jump(Fragment fragment, int requscode) {
        Intent intent = new Intent(fragment.getActivity(), DianZanReasonActivity.class);
        fragment.startActivityForResult(intent, requscode);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dianzan_reason);
        adapter = new DianZanReasonAdapter(labels);
        sadapter = new DianZanReasonAdapter(slabels);
        initView();
    }

    private void initView() {
        title = findViewById(R.id.title_text_title);
        tip = findViewById(R.id.tip);
        tipLayout = findViewById(R.id.empty_layout1);
        emptyLayout2 = findViewById(R.id.empty_layout2);
        tipText = findViewById(R.id.tip_text);
        title.setText("点赞标签");
        tip.setText("为什么赞Ta？");
        tipLayout.setVisibility(View.GONE);
        callBack = findViewById(R.id.title_left_button);
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshlayout);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        searchBarView = findViewById(R.id.searBarView);
        setListener();
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        searchBarView.setOnSearchClicListener(new SearchBarView.Onclick() {
            @Override
            public void onSearchClick(EditText ed, String text) {
                keyWord = text;
                slabels.clear();
//                recyclerView.setAdapter(sadapter);
                spage = 1;
                getLabel();
            }

            @Override
            public void onCanclClick() {
                Log.e("取消", "取消");
                keyWord = "";
                emptyLayout2.setVisibility(View.GONE);
                adapterNotify();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (TextUtils.isEmpty(keyWord)) {
                    labels.clear();
                    page = 1;
                    adapter.notifyDataSetChanged();
                } else {
                    slabels.clear();
                    spage = 1;
                    sadapter.notifyDataSetChanged();
                }
                getLabel();
            }
        });
        refreshLayout.setEnableLoadmore(true);
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (TextUtils.isEmpty(keyWord)) {
                    if (page <= totalpage) {
                        getLabel();
                    } else {
                        refreshlayout.finishLoadmore();
                    }
                } else {
                    if (spage <= totalpage) {
                        getLabel();
                    } else {
                        refreshlayout.finishLoadmore();
                    }
                }
            }
        });
        refreshLayout.autoRefresh();
        sadapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                LabelObject selecLabel = slabels.get(position);
                Intent intent = new Intent();
                intent.putExtra("label", selecLabel);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        adapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                Log.e("2搜索回调", position + "");
                LabelObject selecLabel = labels.get(position);
                Intent intent = new Intent();
                intent.putExtra("label", selecLabel);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
        }
    }

    private void getLabel() {
        if (TextUtils.isEmpty(keyWord)) {
            HttpExcitation.searchEncourageActions(Globals.getToken(), keyWord, page + "", pageSize + "", respose);
        } else {
            HttpExcitation.searchEncourageActions(Globals.getToken(), keyWord, spage + "", pageSize + "", respose);
        }
    }

    AsyncHttpResponseHandler respose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//            recyclerView.setCompleteRefresh();
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadmore();
            String result = new String(responseBody);
            Log.e("标签", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray infoArray = data.optJSONArray("info");
                    totalpage = data.optInt("totalpage");
                    if (TextUtils.isEmpty(keyWord)) {
                        page = page + 1;
                    } else {
                        spage = spage + 1;
                    }
                    for (int i = 0; i < infoArray.length(); i++) {
                        JSONObject info = infoArray.optJSONObject(i);
                        LabelObject labelObject = new LabelObject();
                        labelObject.setActionDesc(info.optString("actionDesc"));
                        labelObject.setActionId(info.optString("actionId"));
                        labelObject.setActionName(info.optString("actionName"));
                        if (TextUtils.isEmpty(keyWord)) {
                            labels.add(labelObject);
                        } else {
                            slabels.add(labelObject);
                        }
                    }
                    adapterNotify();
                } else {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadmore();
                    toast(json.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadmore();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//            recyclerView.setCompleteRefresh();
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadmore();
        }
    };

    private void adapterNotify() {

        if (TextUtils.isEmpty(keyWord)) {
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            if (labels.size() == 0) {
                tipLayout.setVisibility(View.VISIBLE);
                emptyLayout2.setVisibility(View.GONE);
                tipText.setText("什么都没有哦~");
            } else {
                tipLayout.setVisibility(View.GONE);
                emptyLayout2.setVisibility(View.GONE);
            }
        } else {
            recyclerView.setAdapter(sadapter);
            sadapter.notifyDataSetChanged();
            if (slabels.size() == 0) {
                emptyLayout2.setVisibility(View.VISIBLE);
                tipLayout.setVisibility(View.GONE);
                tipText.setText("什么都没有哦~");
            } else {
                tipLayout.setVisibility(View.GONE);
                emptyLayout2.setVisibility(View.GONE);
            }
        }
    }
}
